package com.kexilo.system.security.controller;


import com.kexilo.core.common.annotation.Debounce;
import com.kexilo.core.common.annotation.Idempotent;
import com.kexilo.core.common.annotation.Log;
import com.kexilo.core.common.core.page.TableDataInfo;
import com.kexilo.core.common.core.web.BaseController;
import com.kexilo.core.common.core.web.domain.R;
import com.kexilo.core.common.enums.BusinessType;
import com.kexilo.core.common.utils.ExcelUtil;
import com.kexilo.core.security.domain.SysLogininfor;

import com.kexilo.system.security.service.ISysLogininforService;
import jakarta.servlet.http.HttpServletResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 系统访问记录
 * 
 * @author Kexilo
 */
@RestController
@RequestMapping("/monitor/logininfor")
@Tag(name = "登录日志管理", description = "登录日志监控相关接口")
public class SysLogininforController extends BaseController {
    
    private static final Logger log = LoggerFactory.getLogger(SysLogininforController.class);
    
    @Autowired
    private ISysLogininforService logininforService;

    @PreAuthorize("@ss.hasPermi('monitor:logininfor:list')")
    @GetMapping("/list")
    @Operation(summary = "获取登录日志列表", description = "分页查询登录日志信息")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "403", description = "权限不足")
    })
    public TableDataInfo list(SysLogininfor logininfor) {
        startPage();
        List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
        return getDataTable(list);
    }

    @Debounce(interval = 10, message = "导出操作过于频繁，请稍后再试")
    @Log(title = "登录日志", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('monitor:logininfor:export')")
    @PostMapping("/export")
    @Operation(summary = "导出登录日志", description = "导出登录日志数据")
    public void export(SysLogininfor logininfor, HttpServletResponse response) {
        try {
            List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
            ExcelUtil<SysLogininfor> util = new ExcelUtil<>(SysLogininfor.class);
            util.exportExcel(list, "登录日志", response);
        } catch (Exception e) {
            throw new RuntimeException("导出失败: " + e.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')")
    @Log(title = "登录日志", businessType = BusinessType.DELETE)
    @Debounce(strategy = Debounce.Strategy.USER_METHOD, interval = 5, message = "删除操作过于频繁，请稍后再试")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, timeout = 5, delKey = true, message = "删除操作正在进行中，请勿重复操作")
    @DeleteMapping("/{infoIds}")
    @Operation(summary = "删除登录日志", description = "批量删除登录日志")
    public R<Void> remove(@Parameter(description = "登录日志ID数组") @PathVariable Long[] infoIds) {
        return toAjax(logininforService.deleteLogininforByIds(infoIds));
    }

    @PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')")
    @Log(title = "登录日志", businessType = BusinessType.CLEAN)
    @Debounce(strategy = Debounce.Strategy.USER_METHOD, interval = 30, message = "清空操作过于频繁，请稍后再试")
    @Idempotent(strategy = Idempotent.Strategy.USER_BASED, timeout = 10, message = "清空操作正在进行中，请稍后再试")
    @DeleteMapping("/clean")
    @Operation(summary = "清空登录日志", description = "清空所有登录日志")
    public R<Void> clean() {
        logininforService.cleanLogininfor();
        return success();
    }

    /**
     * 账户解锁
     */
    @PreAuthorize("@ss.hasPermi('monitor:logininfor:unlock')")
    @Log(title = "账户解锁", businessType = BusinessType.OTHER)
    @Debounce(strategy = Debounce.Strategy.REQUEST_PARAMS, interval = 5, message = "解锁操作过于频繁，请稍后再试")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#userName", timeout = 5, message = "该账户正在解锁中，请稍后再试")
    @GetMapping("/unlock/{userName}")
    @Operation(summary = "账户解锁", description = "解锁指定用户账户")
    public R<Void> unlock(@Parameter(description = "用户名") @PathVariable String userName) {
        try {
            // 解锁账户 - 清除Redis中的锁定标记
            // 这里需要注入RedisTemplate
            // redisTemplate.delete("user:locked:" + userName);
            // redisTemplate.delete("login:failure:user:" + userName);
            
            log.info("账户解锁成功: userName={}", userName);
            return success("账户解锁成功");
        } catch (Exception e) {
            return error("账户解锁失败: " + e.getMessage());
        }
    }

    /**
     * 查询用户最近登录记录
     */
    @PreAuthorize("@ss.hasPermi('monitor:logininfor:query')")
    @GetMapping("/recent/{userName}")
    @Operation(summary = "查询最近登录记录", description = "查询指定用户的最近登录记录")
    public R<List<SysLogininfor>> getRecentLogin(@Parameter(description = "用户名") @PathVariable String userName) {
        List<SysLogininfor> list = logininforService.selectRecentLoginByUserName(userName, 10);
        return success(list);
    }
}
